/**
 * Created by admin on 2017/11/13.
 */
/**
 * Created by admin on 2017/10/26.
 */
$(document).ready(function() {

    var VAL = {
        NORMAL : "0000000",
        EVT_USER     : $("#userId").text(),
        T_MIPWOBOM   : "MIPWOBOM",
        T_MWPMTROPE  : "MWPMTROPE",
        T_MTPMTRLAPY : "MTPMTRLAPY",
        T_FBPBISMTR  : "FBPBISMTR",
        T_FBPBISDAT : "FBPBISDAT",
        DISABLED_ATTR : {
            'disabled' : true
        },
        ENABLED_ATTR : {
            'disabled' : false
        }
    };
    var domObj = {
        buttons : {
            $query_btn    	: $("#query_btn"),
            $add_btn    	: $("#add_btn"),
            $update_btn    	: $("#update_btn"),
            $del_btn    	: $("#del_btn"),
            $save_btn    	: $("#save_btn"),
        },
        $applyType      : $("#applyType"),
        $toolNameId     : $("#toolNameId"),
        grids : {
            $toolListDiv 	: $("#toolListDiv"),
            $toolListGrd 	: $("#toolListGrd"),
            $toolListPg 	: $("#toolListPg"),

            $dealListDiv 	: $("#dealListDiv"),
            $dealListGrd 	: $("#dealListGrd"),
            $dealListPg 	: $("#dealListPg")
        },
        dialogs : {
            $mtrlDialog 	: $("#mtrlDialog"),
            $queryBtn    	: $("#queryBtn"),
            $mtrlNameId 	: $("#mtrlNameId"),
            $sureBtn     	: $("#sureBtn"),

            $mtrlListDiv 	: $("#mtrlListDiv"),
            $mtrlListGrd 	: $("#mtrlListGrd"),
            $mtrlListPg 	: $("#mtrlListPg"),

        },
    };
    var rowId,cellName;
    var data=[{
        data_ext :'L',
        data_desc:'L:借用',
    },{
        data_ext :'U',
        data_desc:'U:领用',
    }];
    var iniGridInfo = function(){
        var toolListCM = [
            {name: 'evt_seq_id',       index: 'evt_seq_id',            label: MTRL_PROD_ID_FK,  hidden:true,   width: 100},
            {name: 'mtrl_prod_id_fk',  index: 'mtrl_prod_id_fk',       label: MTRL_PROD_ID_FK,     width: 250},
            {name: 'dest_shop',  index: 'dest_shop',       label: "备品备件仓",     width: 200},
            {name: 'mtrl_name',        index: 'mtrl_name',             label: MTRL_NAME,           width: 200},
            {name: 'apply_cate',       index: 'apply_cate',            label: APPLY_CATE,          width: 100},
            {name: 'apply_mtrl_qty',   index: 'apply_mtrl_qty',        label: APPLY_MTRL_QTY,      width: 250},
            {name: 'evt_note',         index: 'evt_note',              label: EVT_NOTE,            width: 250},
        ];
        domObj.grids.$toolListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            height: 400,
            autowidth: true,
            shrinkToFit:false,
            autoScroll: false,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            multiselect : true,
            cellEdit:true,
            cellsubmit:"clientArray",
            colModel: toolListCM,
            pager: "#toolListPg",
            /*beforeEditCell:function(rowid,cellname,v,iRow,iCol){
                if(cellName=='apply_cate'&&rowId!=null&&cellName!=cellname){
                    var str=domObj.grids.$toolListGrd.jqGrid("getCell",rowId,cellName);
                    if(str=='L:借用'){
                         domObj.grids.$toolListGrd.jqGrid("setCell",rowId,cellName,"L:借用");
                    }else {
                         domObj.grids.$toolListGrd.jqGrid("setCell",rowId,cellName,"U:领用");
                    }
                }
             },
            afterEditCell:function(rowid,cellname,v,iRow,iCol){
                rowId = rowid;
                cellName = cellname;
            },*/
        });
        var dealListCM = [
            {name: 'evt_seq_id',       index: 'evt_seq_id',            label: MTRL_PROD_ID_FK,  hidden:true,   width: 100},
            {name: 'mtrl_prod_id_fk',  index: 'mtrl_prod_id_fk',       label: MTRL_PROD_ID_FK,     width: 250},
            {name: 'dest_shop',  index: 'dest_shop',       label: "备品备件仓",     width: 250},
            {name: 'mtrl_name',        index: 'mtrl_name',             label: MTRL_NAME,           width: 250},
            {name: 'apply_cate',       index: 'apply_cate',            label: APPLY_CATE,          width: 100},
            {name: 'apply_mtrl_qty',   index: 'apply_mtrl_qty',        label: APPLY_MTRL_QTY,      width: 250},
            {name: 'relate_mtrl_qty',  index: 'relate_mtrl_qty', label: RELATE_QTY, width: 100},
            {name: 'evt_note',         index: 'evt_note',              label: EVT_NOTE,            width: 250},
        ];
        domObj.grids.$dealListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            height: 400,
            // width:($("#dealListDiv").width())*0.95,
            width:600,
            autowidth: true,
            shrinkToFit:false,
            autoScroll: false,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            //multiselect : true,
            cellEdit:true,
            cellsubmit:"clientArray",
            colModel: dealListCM,
            pager: "#dealListPg",
        });
        var mtrlListCM = [
            {name: 'mtrl_prod_id_fk',  index: 'mtrl_prod_id_fk',       label:MTRL_PROD_ID_FK,      width: 200},
            {name: 'dest_shop',       index: 'dest_shop',       label:"备品备件仓",      width: 200},
            {name: 'mtrl_name',        index: 'mtrl_name',             label:MTRL_NAME,            width: 200},
            {name: 'mtrl_qty',         index: 'mtrl_qty',              label:MTRL_QTY,             width: 200},
            {name: 'evt_qty',         index: 'evt_qty',              label:EVT_QTY,             width: 200},
            {name: 'mtrl_wh_qty',      index: 'mtrl_wh_qty',           label:MTRL_WH_QTY,          width: 200},
        ];
        domObj.dialogs.$mtrlListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            height: 400,
            // autowidth: true,
            width:$(".container-fluid").width()*0.5,
            shrinkToFit: true,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            multiselect : true,
            emptyrecords: true,
            colModel: mtrlListCM,
            pager: "#mtrlListPg"
        });
    };
    var toolFunc = {
        iniToolTypeSel :function(){
            SelectDom.addSelectArr(domObj.$applyType, data, "data_ext","data_desc","",true);
        },
        iniToolSel :function(){
            var iary={
            		mtrl_cate : 'BACK'
            }
            var inObj = {
                trx_id : VAL.T_FBPBISMTR,
                action_flg : "Q",
                iary : [iary]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr(domObj.$toolNameId, outObj.oary, "mtrl_prod_id","mtrl_prod_dsc","",true);
                SelectDom.addSelectArr(domObj.dialogs.$mtrlNameId, outObj.oary, "mtrl_prod_id","mtrl_prod_dsc","",true);
            }
        },

        initBackDest : function(){
            var inObj = {
                trx_id : VAL.T_FBPBISDAT,
                action_flg : "Q",
                iary : [{
                    data_cate: 'DEST',
                    data_item  : 'C'
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr($("#backDest"), outObj.oary, "data_ext","data_desc","",true);
            }
        },

        initdestShop : function(){
            var inObj = {
                trx_id : VAL.T_FBPBISDAT,
                action_flg : "Q",
                iary : [{
                    data_cate: 'DEST',
                    data_item  : 'C'
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr($("#dest_shop"), outObj.oary, "data_ext","data_desc","",true);
            }
        }
    };
    var btnFunc = {
        queryFunc  :function(){
            //先将编辑状态关闭
            domObj.grids.$toolListGrd.setColProp("apply_cate",{editable:false});
            domObj.grids.$toolListGrd.setColProp("apply_mtrl_qty",{editable:false});
            domObj.grids.$toolListGrd.setColProp("evt_note",{editable:false});
            domObj.grids.$toolListGrd.jqGrid().trigger("reloadGrid");
            var mtrlProdId  = $.trim(domObj.$toolNameId.val());
            var applyType = $.trim(domObj.$applyType.val());
            var destShop = $("#backDest").find("option:selected").val();
            var iary={
                mtrl_prod_id_fk   : mtrlProdId,
                apply_cate        : applyType,
                apply_stat        : "INPR",
                dest_shop : destShop
            }
            var inObj = {
                trx_id : VAL.T_MTPMTRLAPY,
                action_flg : "M",
                evt_usr : VAL.EVT_USER,
                iary : [iary]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                for(var i=0;i<outObj.oaryB.length;i++){
                    if(outObj.oaryB[i].apply_cate=='L'){
                        outObj.oaryB[i].apply_cate='L:借用'
                    }else {
                        outObj.oaryB[i].apply_cate='U:领用'
                    }
                }
                setGridInfo(outObj.oaryB, domObj.grids.$toolListGrd);
            }
        },
        queryDealFunc  :function(){
            var mtrlProdId  = $.trim(domObj.$toolNameId.val());
            var applyType = $.trim(domObj.$applyType.val());
            var iary={
                mtrl_prod_id_fk   : mtrlProdId,
                apply_cate        : applyType,
                apply_stat        : "WAIT"
            }
            var inObj = {
                trx_id : VAL.T_MTPMTRLAPY,
                action_flg : "M",
                evt_usr : VAL.EVT_USER,
                iary : [iary]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                for(var i=0;i<outObj.oaryB.length;i++){
                    if(outObj.oaryB[i].apply_cate=='L'){
                        outObj.oaryB[i].apply_cate='L:借用'
                    }else {
                        outObj.oaryB[i].apply_cate='U:领用'
                    }
                }
                setGridInfo(outObj.oaryB, domObj.grids.$dealListGrd);
            }
        },
        saveFunc  :function(){
            var ids = domObj.grids.$toolListGrd.jqGrid('getGridParam','selarrrow');
            if(ids.length<1){
                showErrorDialog("", "至少选择一条数据进行保存");
                return false;
            }
            var iary =[];
            for(var i=0;i<ids.length;i++) {
                if ($('#toolListGrd :text[role="textbox"]').length > 0) {
                    var v = $('#toolListGrd :text[role="textbox"]').val();
                    $('#toolListGrd :text[role="textbox"]').parent().attr('title', v);
                    $('#toolListGrd :text[role="textbox"]').parent().html(v);
                }
                var rowData = domObj.grids.$toolListGrd.jqGrid("getRowData", ids[i]);
                if(!rowData.apply_cate){
                    showErrorDialog("", "第'"+ $('#' + ids[i])[0].rowIndex +"'行申请类型不能为空");
                    return false;
                }
                if(!rowData.apply_mtrl_qty){
                    showErrorDialog("", "第'"+ $('#' + ids[i])[0].rowIndex +"'行申请数量不能为空");
                    return false;
                }
                if(!ComRegex.isNumber(rowData.apply_mtrl_qty)){
                    showErrorDialog("", "第'"+ $('#' + ids[i])[0].rowIndex +"'行申请数量数值格式不正确！");
                    return false;
                }
                if(rowData.apply_cate=='L:借用'){
                    rowData.apply_cate='L';
                }else {
                    rowData.apply_cate='U';
                }
                var iaryA={
                    evt_seq_id       : rowData.evt_seq_id,
                    mtrl_prod_id_fk  : rowData.mtrl_prod_id_fk,
                    apply_cate       : rowData.apply_cate,
                    apply_mtrl_qty   : rowData.apply_mtrl_qty,
                    evt_note         : rowData.evt_note,
                    dest_shop :  rowData.dest_shop
                }
                iary.push(iaryA);
            }
            var inObj = {
                trx_id : VAL.T_MTPMTRLAPY,
                action_flg : "N",
                evt_usr    : VAL.EVT_USER,
                iary : iary
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                var length = ids.length;
                for(var i=0;i<length;i++) {
                    domObj.grids.$toolListGrd.jqGrid("delRowData",ids[0]);
                }
                showSuccessDialog("保存成功");
            }
        },
        updateFunc   : function(){
            domObj.grids.$toolListGrd.setColProp("apply_cate",{editable:false});
            domObj.grids.$toolListGrd.setColProp("apply_mtrl_qty",{editable:true});
            domObj.grids.$toolListGrd.setColProp("evt_note",{editable:true});
            domObj.grids.$toolListGrd.jqGrid().trigger("reloadGrid");
        },
        delFunc : function(){
            var ids = domObj.grids.$toolListGrd.jqGrid('getGridParam','selarrrow');
            if(ids.length<1){
                showErrorDialog("", "至少选择一条数据进行删除");
                return false;
            }
            var rowData = domObj.grids.$toolListGrd.jqGrid("getRowData", ids[0]);
            if(rowData.evt_seq_id==""){
                showErrorDialog("", "新增状态无法进行删除操作");
                return false;
            }
            $("#del_btn").showCallBackWarnningDialog({
                errMsg  : "是否删除备品备件信息,请确认!!!!",
                callbackFn : function(data) {
                    if(data.result==true){
                        var iary =[];
                        for(var i=0;i<ids.length;i++) {
                            var rowData = domObj.grids.$toolListGrd.jqGrid("getRowData", ids[i]);
                            if(rowData.apply_cate=='L:借用'){
                                rowData.apply_cate='L';
                            }else {
                                rowData.apply_cate='U';
                            }
                            var iaryA={
                                evt_seq_id       : rowData.evt_seq_id,
                                mtrl_prod_id_fk  : rowData.mtrl_prod_id_fk,
                                apply_cate       : rowData.apply_cate,
                                apply_mtrl_qty   : rowData.apply_mtrl_qty,
                                evt_note         : rowData.evt_note
                            }
                            iary.push(iaryA);
                        };
                        var inObj = {
                            trx_id : VAL.T_MTPMTRLAPY,
                            action_flg : "C",
                            iary : iary
                        };
                        var outObj = comTrxSubSendPostJson(inObj);
                        if (outObj.rtn_code == VAL.NORMAL) {
                            var length = ids.length;
                            for(var i=0;i<length;i++){
                                domObj.grids.$toolListGrd.jqGrid("delRowData",ids[0]);
                            }
                            showSuccessDialog("删除成功");
                        }
                    }
                }
            });
        },
        dialogQueryFunc  :function(){
            var mtrlProdId = $.trim(domObj.dialogs.$mtrlNameId.val());
            var dest_shop = $("#dest_shop").find("option:selected").val();
            if(!dest_shop){
                showErrorDialog("","请选择备品备件仓");
                return false;
            }
            var iary={
                dest_shop : dest_shop,
                mtrl_prod_id_fk : mtrlProdId
            }
            
            var inObj = {
                trx_id : VAL.T_MWPMTROPE,
                action_flg : "Q",
                iary : [iary]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj.oary, domObj.dialogs.$mtrlListGrd);
            }
        },
        dialogSureFunc  :function(){
            var ids = domObj.dialogs.$mtrlListGrd.jqGrid('getGridParam','selarrrow');
            if(ids.length<1){
                showErrorDialog("", "至少选择一条数据进行保存");
                return false;
            }
            var oary =[];
            for(var i=0;i<ids.length;i++) {
                var rowData = domObj.dialogs.$mtrlListGrd.jqGrid("getRowData", ids[i]);
                var iaryA={
                    mtrl_prod_id_fk  : rowData.mtrl_prod_id_fk,
                    mtrl_name        : rowData.mtrl_name,
                    dest_shop : rowData.dest_shop,
                    mtrl_wh_qty : rowData.mtrl_wh_qty
                }
                oary.push(iaryA);
            }
            domObj.grids.$toolListGrd.jqGrid("clearGridData");//清空主grid中的数据
            setGridInfo(oary, domObj.grids.$toolListGrd);//将数据set进入主grid
            domObj.dialogs.$mtrlDialog.modal("hide");//将对话框隐藏
            var allId = domObj.grids.$toolListGrd.jqGrid('getDataIDs');
            domObj.grids.$toolListGrd.setColProp("apply_cate",{editable:true,edittype:"select",editoptions: {value: {'L':'L:借用', 'U':'U:领用'}}});
            domObj.grids.$toolListGrd.setColProp("apply_mtrl_qty",{editable:true});
            domObj.grids.$toolListGrd.setColProp("evt_note",{editable:true});
            domObj.grids.$toolListGrd.jqGrid().trigger("reloadGrid");
        }
    };

    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.iniToolTypeSel();
        toolFunc.iniToolSel();
        toolFunc.initBackDest();
        toolFunc.initdestShop();
    };
    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        domObj.buttons.$query_btn.click(function(){
            btnFunc.queryFunc();
            btnFunc.queryDealFunc();
        });
        domObj.buttons.$add_btn.click(function(){
            domObj.dialogs.$mtrlDialog.modal({
                backdrop: true,
                keyboard: false,
                show: false
            });
            domObj.dialogs.$mtrlDialog.modal("show");
            // btnFunc.dialogQueryFunc();
        });
        domObj.buttons.$save_btn.click(function(){
            btnFunc.saveFunc();
        });
        domObj.buttons.$del_btn.click(function(){
            btnFunc.delFunc();
        });
        domObj.buttons.$update_btn.click(function(){
            btnFunc.updateFunc();
        });
       /* domObj.dialogs.$queryBtn.click(function(){
            btnFunc.dialogQueryFunc();
        });*/
        domObj.dialogs.$mtrlNameId.change(function(){
            btnFunc.dialogQueryFunc();
        });

       $("#dest_shop").change(function(){
            btnFunc.dialogQueryFunc();
        });

        domObj.dialogs.$sureBtn.click(function(){
            btnFunc.dialogSureFunc();
        });

    };
    /**
     * Other action bind
     */
    var otherActionBind = function(){
        $("form").submit(function(){
            return false;
        });
    };
    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniContorlData();
        iniButtonAction();
        otherActionBind();
    };

    initializationFunc();
    //表格自适应
    function resizeFnc(){
        var offsetBottom, divWidth,offsetBottom1, divWidth1;
        divWidth = $("#bottomDiv").width();
        offsetBottom =  $(window).height() - $("#bottomDiv").offset().top;
        $("#bottomDiv").height(offsetBottom * 0.95);
        $("#toolListGrd").setGridWidth(divWidth * 0.85);
        $("#toolListGrd").setGridHeight(offsetBottom * 0.99 - 51);
        //2
        divWidth1= $("#divTotal").width();
        offsetBottom1 =  $(window).height() - $("#divTotal").offset().top;
        $("#divTotal").height(offsetBottom1 * 0.95);
        $("#dealListGrd").setGridWidth(divWidth1 * 0.85);
        $("#dealListGrd").setGridHeight(offsetBottom1 * 0.99 - 51);

    };
    resizeFnc();
    $(window).resize(function() {
        resizeFnc();
    });
});
